package com.quickstart.common.file;

import com.quickstart.common.date.DateTimeUtils;
import com.quickstart.common.other.FileConstant;
import com.quickstart.common.other.PropertyUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 文件工具类
 *
 *
 */
public class FileUtils {


    public static String[] getFileName(String uploadPath, String prefix) {

        String[] fileNameArray = new String[3];
        Map<String, String> systemMap = PropertyUtil.getMapByPropertyFile("system.properties");
        String basePath = (String) systemMap.get("upload_path");
        String pdfPath = (String) systemMap.get(uploadPath);
        String datePath = DateTimeUtils.convertDate(new Date(), 2);
        String filePath = basePath + File.separator + pdfPath + File.separator + datePath;
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
        String pdfName = prefix + "_" + DateTimeUtils.convertDate(new Date(), 4) + ".pdf";
        String fileName = filePath + File.separator + pdfName;

        fileNameArray[0] = pdfName;
        fileNameArray[1] = fileName;
        fileNameArray[2] = pdfPath + File.separator + datePath + File.separator + pdfName;

        return fileNameArray;
    }


    public static Map<String, Object> fileUpload(MultipartHttpServletRequest multipartRequest,
                                                 String uploadKey, String propKey, String aliasName) {

        // 获取上传文件
        Map<String, Object> fileMap = new HashMap<String, Object>();
        Iterator<String> fileIter = multipartRequest.getFileNames();
        // 多文件
        while (fileIter.hasNext()) {
            MultipartFile uploadFile = multipartRequest.getFile(fileIter.next());
            // 获取文件大小
            long fileSize = uploadFile.getSize();
            //文件大小超过最大值
            if (fileSize > FileConstant.FILE_MAX_SIZE) {
                fileMap.put(FileConstant.ERROR_STATUS, FileConstant.FILE_EXCEED_INFO);
                return fileMap;
            } else {
                //文件名
                String fileName = uploadFile.getOriginalFilename();
                //文件类型
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                Map<String, String> systemMap = PropertyUtil
                        .getMapByPropertyFile("system.properties");
                if (StringUtils.isNotBlank(uploadKey)) {
                    //获取基本上传路径 D://upload
                    String baseUploadPath = systemMap.get(uploadKey);
                    //虚拟拼接路径 vehicle/vt
                    String propPath = "";
                    if (StringUtils.isNotBlank(propKey)) {
                        propPath = systemMap.get(propKey);
                    }
                    //eg:20150818
                    String datePath = DateTimeUtils.convertDate(new Date(), 2);
                    // 如果没有对应目录 则创建目录
                    File file = new File(baseUploadPath + File.separator + propPath
                            + File.separator + datePath);
                    // 判断路径是否存在
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    int randomNum = RandomUtils.nextInt(1000000);
                    String fullName = "";
                    if (StringUtils.isNotBlank(propPath)) {
                        fullName = baseUploadPath + File.separator + propPath + File.separator
                                + datePath + File.separator + aliasName + "_" + randomNum
                                + fileType;
                    } else {
                        fullName = baseUploadPath + File.separator + datePath + File.separator
                                + aliasName + "_" + randomNum + fileType;
                    }
                    try {
                        FileCopyUtils.copy(uploadFile.getBytes(), new File(fullName));
                        fileMap.put("fileName", fileName);
                        fileMap.put("fileType", fileType);
                        fileMap.put("fileBaseUploadPath", baseUploadPath);
                        fileMap.put("fileFullPath", fullName.replace("\\", "/"));
                        fileMap.put("filePath",
                                fullName.replace(baseUploadPath, "").replace("\\", "/"));
                        fileMap.put("fileSize", fileSize);
                    } catch (IOException e) {
                        //e.printStackTrace();
                        //文件上传失败
                        fileMap.put(FileConstant.ERROR_STATUS, FileConstant.ERROR_INFO);
                        return fileMap;
                    }
                }
            }
        }
        return fileMap;
    }

    /**
     * 通用文件下载
     *
     * @param downloadFile 待下载文件
     * @param fileName     文件名
     * @param response
     * @param request
     * @param fileType     文件类型 1：PDF 2.附件文件 ...
     * @throws UnsupportedEncodingException

     */
    public static void downloadFile(File downloadFile, String fileName,
                                    HttpServletResponse response, HttpServletRequest request, int fileType)
            throws UnsupportedEncodingException {

        if (downloadFile.exists()) {
            //				fileName = URLEncoder.encode(downloadFile.getName(), "utf-8");
            fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
            switch (fileType) {
                case 1:
                    //PDF格式头
                    response.setContentType("application/pdf");
                    break;
                default:
                    response.setContentType("application/x-msdownload");
                    break;
            }
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            int fileLength = (int) downloadFile.length();
            response.setContentLength(fileLength);
            if (fileLength != 0) {
                InputStream in = null;
                ServletOutputStream out = null;
                try {
                    in = new FileInputStream(downloadFile);
                    out = response.getOutputStream();
                    int count = 0;
                    byte[] b = new byte[1024];
                    while ((count = in.read(b)) != -1) {
                        out.write(b, 0, count);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != in) {
                            in.close();
                        }
                        if (null != out) {
                            out.flush();
                            out.close();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

    }


    /**
     * 读取文本文件
     * @param filePath
     * @return
     */
    public static List<String> readTxtFile(String filePath){
        List<String> list = new ArrayList<>();

        File file = new File(filePath);
        if(!file.exists()){
            return null;
        }

        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"UTF-8");
            BufferedReader br = new BufferedReader(reader);

            String line = null;
            while ((line = br.readLine())!= null ) {
                list.add(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}
